package org.hzz.redis;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author <a href="mailto:1193094618@qq.com">pkmer</a>
 * <br>
 * <a href = "https://gitee.com/developeros/videos-online">Code Repository</a>
 * At 2024/9/8
 */
@Slf4j
public class SemaphoreTest {

    public static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
    public static ScheduledFuture<?> scheduledFuture;
    public static AtomicInteger count = new AtomicInteger(1);
    public static void main(String[] args) throws InterruptedException {
        run();
    }
    public static void run(){
        scheduledFuture = executor.schedule(() -> {
            log.info("执行 -> {}",count.incrementAndGet());
            run();
        },3, TimeUnit.SECONDS);

        if(count.get() > 3){
            log.info("cancel -> {}",count.get());
            scheduledFuture.cancel(false);
        }
    }

    public static void testSemaphore() throws InterruptedException {
        Semaphore latch = new Semaphore(0);
        int nums = 5;
        for(int i = 0; i< nums; i++){
            CompletableFuture.runAsync(() -> {
                try {
                    log.info("{}", Thread.currentThread().getId());
                    latch.tryAcquire(3, TimeUnit.SECONDS);
                    log.info("after 3 seconds {}", Thread.currentThread().getId());
                    latch.release();
                } catch (InterruptedException ignore) {}
            });
        }

        latch.acquire(nums);
        log.info("all done");
    }
}
